//
//  fileIO.m
//  Gradekeeper0.2
//
//  Created by Lily Wang on 11/2/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//  Reference: http://www.servin.com/iphone/iPhone-File-IO.html

#import "fileIO.h"


@implementation fileIO


+ (void) writeToFile: (NSString *) fname: (NSString *)fcontent{

	
	NSString *path = [fileIO getFilePath: fname];
	[fcontent writeToFile:path
			  atomically:YES
				encoding:NSStringEncodingConversionAllowLossy 
				   error:nil];
	
	
} //writeToFile

+ (NSString *) readFromFile:  (NSString *) fname{
	NSString *path = [fileIO getFilePath: fname];
	NSString *fileContents = [NSString stringWithContentsOfFile:path
														  encoding:NSUTF8StringEncoding
															 error:nil];
	return fileContents;
	
} //readFromFile

+ (NSString *) getFilePath: (NSString *) fileName{
	NSArray *arrayPaths = 
	NSSearchPathForDirectoriesInDomains(
										NSDocumentDirectory,
										NSUserDomainMask,
										YES);
	
	NSString *docDir = [arrayPaths objectAtIndex:0];
	
	NSString *fname = [NSString stringWithFormat:@"/%@.txt", fileName];
	NSString *filePath = [docDir stringByAppendingString:fname];
	return filePath;	
} //getFilePath

+ (BOOL) fileExist: (NSString *) fName{
	if ([fileIO readFromFile:fName] == NULL){
		return NO;
	} else {
		return YES;
	}	
} //fileExist

+ (void) appendToFile: (NSString *) fName: (NSString *) appendContent{
	NSString *tempContent = [fileIO readFromFile:fName];
	NSString *toWrite = [NSString stringWithFormat:@"%@:%@", tempContent, appendContent];
	[fileIO writeToFile:fName:toWrite];
} //apendToFile

+ (void) deleteFromFile: (NSString *) fName: (NSString *) deleteContent :(NSString *) delimiter{
	NSString *tempContent = [fileIO readFromFile:fName];
	NSString *toDelete = [NSString stringWithFormat:@"%@%@",delimiter,deleteContent];
	NSString *resultContent = [tempContent stringByReplacingOccurrencesOfString:toDelete withString:@""];
	[fileIO writeToFile:fName:resultContent];
	
} //deleteFromFile

@end

